/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[欢迎加盟知启蒙，一起邂逅框架梦]
 * 
 * https://www.zhiqim.com/gitcan/zhiqim/zhiqim_account.htm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.zhiqim.account.presenter;

import org.zhiqim.account.ZacConstants;
import org.zhiqim.account.ZacSessionUser;
import org.zhiqim.account.dao.UserTradeDao;
import org.zhiqim.account.dbo.user.UserInfo;
import org.zhiqim.account.dbo.user.UserTrade;
import org.zhiqim.account.paycallback.PayCallback;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.annotation.AnIntercept;
import org.zhiqim.kernel.Global;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.util.Ids;
import org.zhiqim.kernel.util.Sqls;
import org.zhiqim.kernel.util.Strings;
import org.zhiqim.orm.ZTable;
import org.zhiqim.orm.dbo.Selector;

@AnIntercept("chkZacLogin")
@AnAlias("BalancepayPresenter")
public class BalancepayPresenter implements ZacConstants
{
    public static void Balancepay(HttpRequest request) throws Exception
    {
        int tradeAmount = request.getParameterAmount2R("tradeAmount");
        String tradeSubject = request.getParameter("tradeSubject");
        String tradeCallback = request.getParameter("tradeCallback");
        long tradeOrderId = request.getParameterLong("tradeOrderId", 0);
        long tradeId = Ids.longId(PAY_SEQ);
        
        //验证用户余额
        ZacSessionUser sessionUser = request.getSessionUser(ZacSessionUser.class);
        UserInfo userInfo = Global.get(ZTable.class).item(UserInfo.class, new Selector("userBalance", "userId", sessionUser.getUserId()));
        if (userInfo.getUserBalance() < tradeAmount)
        {
            request.setResponseError("用户余额不足，请充值后再支付或更换支付方式");
            return;
        }
        
        //组装余额支付数据
        UserTrade balancePay = new UserTrade();
        balancePay.setUserId(sessionUser.getUserId());
        balancePay.setTradeId(tradeId);
        balancePay.setTradeAmount(tradeAmount);
        balancePay.setTradePartySubject(tradeSubject);
        balancePay.setTradePartyNo(Strings.toString(tradeOrderId));
        balancePay.setTradeTime(Sqls.nowTimestamp());
        
        //更新用户账户
        UserTradeDao.doExpend(balancePay);
        
        //支付回调
        Object obj = Global.getCreate(Global.getClass(tradeCallback));
        PayCallback call = (PayCallback)obj;
        String redirectUrl = call.call(balancePay);
        
        request.setResponseResult(redirectUrl);
    }

}
